package com.backstage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.backstage.dao.ContactsTagMapper;
import com.backstage.dao.ContactsTagRelationMapper;
import com.backstage.dao.ContactsUserMapper;
import com.backstage.pojo.*;
import com.backstage.service.ContactsUserService;
import com.backstage.utils.CommonDate;
import com.backstage.utils.PageBean;
import com.backstage.utils.UrlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ContactsUserServiceImpl implements ContactsUserService {
    @Autowired
    private ContactsUserMapper contactsUserMapper;
    @Autowired
    private ContactsTagMapper contactsTagMapper;
    @Autowired
    private ContactsTagRelationMapper contactsTagRelationMapper;

    public PageBean<ContactsUser> selectUserList(int pageNum, int pageSize, String tag) {
        PageBean<ContactsUser> pageBean = new PageBean<ContactsUser>();

        ContactsUser newContactsUser = new ContactsUser();
        if (!"".equals(tag)) {
            newContactsUser.setTags(tag);
        }

        PageHelper.startPage(pageNum, pageSize);
        List<ContactsUser> userList = contactsUserMapper.selectUserList(newContactsUser);
        PageInfo<ContactsUser> userPageInfo = new PageInfo<ContactsUser>(userList);
        pageBean.setList(userList);
        pageBean.setPageBeanObj(userPageInfo.getPageNum(), userPageInfo.getPageSize(), userPageInfo.getNextPage(), userPageInfo.getPrePage(), userPageInfo.getTotal(), userPageInfo.getPages());

        return pageBean;
    }

    //查询用户标签
    public List<ObjectContactsUser> selectUserTagList(Integer userId) {
        return contactsUserMapper.selectUserTagList(userId);
    }

    //查询用户关联的标签数量
    public Integer selectTagRelationTotal(Integer userid){
        return contactsUserMapper.selectTagRelationTotal(userid);
    };

    //新增标签
    @Transactional
    public List<ObjectContactsUser> insertContactsTag(Integer userId, String tagName) {
        //判断Tab是否存在
        Integer tagId = contactsUserMapper.selectContactsUserTagName(tagName);
        if (tagId == null) {
            //新增Tab标签
            ContactsTag newContactsTag = new ContactsTag();
            newContactsTag.setTagname(tagName);
            newContactsTag.setTagnum(0);
            contactsUserMapper.insertAddContactsTag(newContactsTag);
            tagId = newContactsTag.getTagid();

        }

        //判断Tab关联表是否存在
        Integer relationIdCount = contactsUserMapper.selectRelationHasId(userId, tagId);
        if (relationIdCount == null) {
            //建立Tab关系表
            contactsUserMapper.insertAddRelationId(userId, tagId);
            //更新Tab引用数量+1
            contactsUserMapper.updateContactsTagNumAd(tagId);
        }

        List<ObjectContactsUser> objectContactsUser = contactsUserMapper.selectUserTagList(userId);
        ArrayList<String> tagArrString = new ArrayList<String>();
        for (ObjectContactsUser item : objectContactsUser) {
            tagArrString.add(item.getTagname());
        }
        ContactsUser newContactsUser = new ContactsUser();
        newContactsUser.setId(userId);
        newContactsUser.setTags(String.join(",", tagArrString));
        contactsUserMapper.updateByPrimaryKeySelective(newContactsUser);

        return objectContactsUser;
    }

    //删除标签
    @Transactional
    public List<ObjectContactsUser> deleteContactsTag(Integer userId, Integer tagId) {
        int hasDeleteSuccess = contactsUserMapper.deleteRelationTagKey(userId, tagId);
        System.out.println(hasDeleteSuccess);

        //更新用户 Tags 字段内容
        List<ObjectContactsUser> objectContactsUser = contactsUserMapper.selectUserTagList(userId);
        ArrayList<String> tagArrString = new ArrayList<String>();
        for (ObjectContactsUser item : objectContactsUser) {
            tagArrString.add(item.getTagname());
        }
        ContactsUser newContactsUser = new ContactsUser();
        newContactsUser.setId(userId);
        newContactsUser.setTags(String.join(",", tagArrString));
        contactsUserMapper.updateByPrimaryKeySelective(newContactsUser);

        return objectContactsUser;
    }

    //查询某用户ID，下级所有关联用户
    public List<ContactsRelationUser> selectUserDetailsList(Integer userId, String tagName){
        List<ContactsRelationUser> newContactsRelationUser = contactsUserMapper.selectUserDetailsListKey(userId, tagName);
        return newContactsRelationUser;
    };






    //查询某用户ID，下级所有关联用户  微信小程序 简约版数据
    public List<WeixinAppUser> selectUserDetailsListWxId(Integer userId){
        List<WeixinAppUser> newContactsRelationUser = contactsUserMapper.selectUserDetailsListKeyWxId(userId);
        return newContactsRelationUser;
    };
    public List<WeixinAppUser> selectUserDetailsListWx(Integer userId, String tagName){
        List<WeixinAppUser> newContactsRelationUser = contactsUserMapper.selectUserDetailsListKeyWx(userId, tagName);
        return newContactsRelationUser;
    };

    //查询用户详情 微信
    @Override
    public WeixinAppUser selectUserObjKeyWx(Integer userId) {
        return contactsUserMapper.selectUserObjKeyWx(userId);
    }

    //新增标签 微信小程序
    @Transactional
    public List<ObjectContactsUser> insertContactsTagWx(Integer userId, String tagName) {
        //判断Tab是否存在
        Integer tagId = contactsUserMapper.selectContactsUserTagName(tagName);
        if (tagId == null) {
            //新增Tab标签
            ContactsTag newContactsTag = new ContactsTag();
            newContactsTag.setTagname(tagName);
            newContactsTag.setTagnum(0);
            contactsUserMapper.insertAddContactsTag(newContactsTag);
            tagId = newContactsTag.getTagid();
        }

        //判断Tab关联表是否存在
        Integer relationIdCount = contactsUserMapper.selectRelationHasId(userId, tagId);
        if (relationIdCount == null) {
            //建立Tab关系表
            contactsUserMapper.insertAddRelationId(userId, tagId);
            //更新Tab引用数量+1
            contactsUserMapper.updateContactsTagNumAd(tagId);
        }

        List<ObjectContactsUser> objectContactsUser = contactsUserMapper.selectUserTagList(userId);
        ArrayList<String> tagArrString = new ArrayList<String>();
        for (ObjectContactsUser item : objectContactsUser) {
            tagArrString.add(item.getTagname());
        }
        ContactsUser newContactsUser = new ContactsUser();
        newContactsUser.setId(userId);
        newContactsUser.setTags(String.join(",", tagArrString));
        contactsUserMapper.updateByPrimaryKeySelective(newContactsUser);

        return objectContactsUser;
    }

    //删除标签 小程序
    @Transactional
    public List<ObjectContactsUser> deleteContactsTagWx(Integer userId, Integer tagId) {
        int hasDeleteSuccess = contactsUserMapper.deleteRelationTagKey(userId, tagId);
        System.out.println(hasDeleteSuccess);
        //更新用户 Tags 字段内容
        List<ObjectContactsUser> objectContactsUser = contactsUserMapper.selectUserTagList(userId);
        ArrayList<String> tagArrString = new ArrayList<String>();
        for (ObjectContactsUser item : objectContactsUser) {
            tagArrString.add(item.getTagname());
        }
        ContactsUser newContactsUser = new ContactsUser();
        newContactsUser.setId(userId);
        newContactsUser.setTags(String.join(",", tagArrString));
        contactsUserMapper.updateByPrimaryKeySelective(newContactsUser);

        return objectContactsUser;
    }



    //验证Code 小程序
    @Transactional
    public ContactsUser selectCodeUserWx(String wxCode, Integer fasongId, WeixinUserInfo userInfo) {
        //请求微信api获取用户的openid和sessionKey
        JSONObject jsonObject = getUserWXLoginInfo(wxCode);
        ContactsUser newContactsUser = new ContactsUser();
        if(jsonObject!=null && !jsonObject.containsKey("openid")) {
            return newContactsUser;
        }
        String openid = (String)jsonObject.get("openid");
        String sessionKey = (String)jsonObject.get("session_key");
        System.out.println(openid);
        System.out.println(sessionKey);

        //通过openid查询数据库是否有此用户
        ContactsUser selectContactsUser = contactsUserMapper.selectContactsUserOpenid(openid);
        if(selectContactsUser!=null) {//用户已存在
            return selectContactsUser;
        }

        newContactsUser.setOpenid(openid);
        newContactsUser.setContactsid(fasongId);
        newContactsUser.setAvatarurl(userInfo.getAvatarUrl());
        newContactsUser.setCity(userInfo.getCity());
        newContactsUser.setCountry(userInfo.getCountry());
        newContactsUser.setGender(userInfo.getGender());
        newContactsUser.setLanguage(userInfo.getLanguage());
        newContactsUser.setNickname(userInfo.getNickName());
        newContactsUser.setProvince(userInfo.getProvince());
        newContactsUser.setCreatetime(CommonDate.newData());
        int hasPushok = contactsUserMapper.insertSelective(newContactsUser);
        ContactsUser returnUserMap = new ContactsUser();
        if(hasPushok==1){
            returnUserMap = contactsUserMapper.selectContactsUserOpenid(openid);
        }
        return returnUserMap;
    }

    private JSONObject getUserWXLoginInfo(String wxCode) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> requestUrlParam = new HashMap<String,String>();
        requestUrlParam.put("appid", "wx40d43ec3013bd439");	//开发者设置中的appId
        requestUrlParam.put("secret", "2afbc36a0de5116cf1694d3638d252d0");	//开发者设置中的appSecret
        requestUrlParam.put("js_code", wxCode);	//小程序调用wx.login返回的code
        requestUrlParam.put("grant_type", "authorization_code");	//默认参数
        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
        JSONObject jsonObject = JSON.parseObject(UrlUtil.sendPost(requestUrl, requestUrlParam));
        return jsonObject;
    }


    //查询某个用户
    public ContactsUser selectContactsUserKey(Integer userId){
        return contactsUserMapper.selectByPrimaryKey(userId);
    }
    //查询某个用户
    public WeixinAppUser selectContactsUserKeyWx(Integer userId){
        return contactsUserMapper.selectUserObjKeyWx(userId);
    }

}